package org.openurp.edu.student.info.web.action

import java.io.FileOutputStream
import org.beangle.commons.codec.digest.Digests
import org.beangle.commons.io.IOs
import org.beangle.commons.lang.Strings
import org.beangle.data.dao.{ EntityDao, OqlBuilder }
import org.beangle.webmvc.api.action.{ ActionSupport, ServletSupport }
import org.beangle.webmvc.api.context.Params
import org.beangle.webmvc.api.view.View
import org.beangle.webmvc.entity.action.RestfulAction
import org.openurp.edu.student.info.model.{ Schooling, Semester, Student, StudentWai, Visa }
import org.openurp.edu.student.info.service.StudentPortraitService
import javax.servlet.http.Part
import org.beangle.commons.lang.Numbers

/**
 * @author King Sun
 */
class PayrecordAction extends ActionSupport with ServletSupport {
  var studentPortraitService: StudentPortraitService = _
  var entityDao: EntityDao = _

  def index(): String = {
    val sno = get("sno", request.getSession.getAttribute("code"))
    val builder = OqlBuilder.from(classOf[Schooling], "s").where("s.code =:code", sno)
    put("students", entityDao.search(builder))
    forward()
  }
  def visa(): String = {
    val semesterId = Numbers.toInt(get("student.semester.id").orNull, 0)
    put("semester", (entityDao.search(OqlBuilder.from(classOf[Semester], "semester").where("semester.id=:id", semesterId))).head)
    forward()
  }

  def update(): View = {
    val builder = OqlBuilder.from(classOf[Student], "s").where("s.code = :code", request.getSession.getAttribute("code"))
    val users = entityDao.search(builder).head
    val semesterId = Numbers.toInt(get("student.semester.id").orNull, 0)
    val semester = entityDao.search(OqlBuilder.from(classOf[Semester], "semester").where("semester.id=:id", semesterId)).head
    val parts = Params.getAll("visas").asInstanceOf[List[Part]]
    parts foreach { part =>
      val visa = new Visa()
      visa.fileSize = part.getSize.toInt
      val ext = Strings.substringAfterLast(part.getSubmittedFileName, ".")
      visa.path = Digests.md5Hex(part.getSubmittedFileName) + (if (Strings.isEmpty(ext)) "" else "." + ext)
      visa.name = part.getSubmittedFileName
      visa.semester = semester
      visa.updatedAt = new java.util.Date
      IOs.copy(part.getInputStream, new FileOutputStream(studentPortraitService.headPortaitBase + visa.path))

      if (users.studentWai == null) {
        users.studentWai = new StudentWai
      }
      visa.studentWai = users.studentWai
      users.studentWai.visas += visa
    }
    if (users.studentWai != null) {
      entityDao.saveOrUpdate(users.studentWai, users)
    } else {
      entityDao.saveOrUpdate(users)
    }
    redirect(to(classOf[HomeAction], "index"), "")
  }
}
